﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SmartCity.Shared;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace MetroManagement
{
    /// <summary>
    /// 站点应用服务类
    /// </summary>
    public class StationAppService : ApplicationService, IStationAppService
    {
        private readonly IRepository<LineStation> _lineStationRepository;

        public StationAppService(
            IRepository<LineStation> lineStationRepository)
        {
            _lineStationRepository = lineStationRepository;
        }

        // 列表
        public async Task<ResultResponse<IList<UniteStationDto>>> ListAsync(int? lineId = null, string name = null)
        {
            var query = await _lineStationRepository
                .WithDetailsAsync(m => m.Line, m => m.Station);
            var stations = await _lineStationRepository
                .WhereIf(lineId.HasValue, m => m.LineId == lineId.Value)
                .WhereIf(!string.IsNullOrWhiteSpace(name), m => m.Station.Name == name)
                .Select(m => m.Station)
                .Distinct()
                .ToListAsync();
            var dtos = new List<UniteStationDto>(stations.Count);
            foreach (var station in stations)
            {
                var lines = await query
                    .Where(m => m.StationId == station.Id)
                    .Select(m => m.Line)
                    .ToListAsync();
                if (lines.Any())
                {
                    var lineDtos = ObjectMapper.Map<List<Line>, List<SimpleLineDto>>(lines);
                    dtos.Add(new UniteStationDto()
                    {
                        Name = station.Name,
                        Lines = lineDtos
                    });
                }
            }
            return ResultResponse<IList<UniteStationDto>>.Successful(dtos);
        }
    }
}